<template>
  <uni-nav-bar title="预约加注" color="#333" left-icon="left" @clickLeft="redirectTo('index/filling')" statusBar></uni-nav-bar>
  <!-- <environment></environment> -->
  <view class="flex-col-hcenter">
    <view class="box">
      <view class="card">
        <view class="tab-box" :class="curTab">
          <view class="flex-center" :class="isStation ? 'active' : 'tab'" @click="switchTab('station')">进站加注</view>
          <view class="flex-center" :class="isDelivery ? 'active' : 'tab'" @click="switchTab('delivery')">
            配送到车
          </view>
        </view>
        <!-- time -->
        <view class="item-box split-line">
          <text>预约时间</text>
          <view class="pick-block" @click="openTimePicker">
            <text v-show="time === ''" class="tar c-999">点击选择预约时间</text>
            <text v-show="time !== ''" class="tar">{{ time }}</text>
            <view class="tar"><uni-icons type="right" color="#999"></uni-icons></view>
          </view>
        </view>
        <!-- plate number -->
       <view class="item-box split-line">
          <text>车牌号</text>
          <view class="pick-block" @click="openPlatePicker">
            <text v-show="plateNumber === ''" class="tar c-999">点击选择车辆信息</text>
            <text v-show="plateNumber !== ''" class="tar">{{ plateNumber }}</text>
            <view class="tar"><uni-icons type="right" color="#999"></uni-icons></view>
          </view>
        </view>
        <!-- weight -->
        <view class="item-box split-line">
          <text>加注量</text>
          <view class="pick-block" @click="openWeightPicker">
            <text v-show="weight === null" class="tar c-999">点击选择加注量</text>
            <text v-show="weight !== null" class="tar">{{ weight }}公斤</text>
            <view class="tar"><uni-icons type="right" color="#999"></uni-icons></view>
          </view>
        </view>
        <!-- location -->
        <view class="item-box split-line">
          <text v-show="isStation">加注机</text>
          <text v-show="isDelivery">加注地址</text>
          <view v-show="isStation" class="pick-block" @click="openMachinePicker">
            <text v-show="stationInfo.location === ''" class="tar c-999">点击选择加注机</text>
            <text v-show="stationInfo.location !== ''" class="tar">{{ stationInfo.location }}</text>
            <view class="tar"><uni-icons type="right" color="#999"></uni-icons></view>
          </view>
		  <!-- @click="navTo('appointment/address')" -->
          <view v-show="isDelivery" class="map-address-block" @click="openMap">
            <view class="flex-jcfe">
              <text>{{ Locposition?Locposition:deliveryInfo.location?deliveryInfo.location:'请录入驻车地址' }}</text>
            </view>
            <view class="tar"><uni-icons type="location-filled" color="#999" size="24"></uni-icons></view>
          </view>
        </view>
        <!-- address -->
        <view class="item-box">
          <text>详细地址</text>
          <view class="flex-jcfe">
			 <textarea
			    v-show="isDelivery"
			    v-model="Detailed"
			    :placeholder="deliveryInfo.address?deliveryInfo.address:'请输入您的详细地址'"
			    placeholder-style="color: #666;font-size: 32rpx"
			    auto-height
			    class="detail-textarea"
			  ></textarea>
            <text v-show="isStation">{{ stationInfo.address }}</text>
            <!-- <text v-show="isDelivery">{{ deliveryInfo.address }}</text> -->
          </view>
        </view>
      </view>
	  <view class="informatio">
	  	<view class="">
	  		<text>姓名</text>
			<input type="text" :placeholder="deliveryInfo.name?deliveryInfo.name:userInfo.realname ? userInfo.realname:'请填写姓名'" v-model="name" maxlength="11"/>
	  	</view>
		<view class="">
			<text>电话</text>
			<input type="number" :placeholder="deliveryInfo.phone?deliveryInfo.phone:userInfo.mobile?userInfo.mobile:'请填写联系电话'" v-model="phone" maxlength="11"/>
		</view>
	  </view>
      <view class="card gift-box" v-if="giftArr && giftArr.length > 0">
        <view class="title">福利</view>
        <view class="content">
          车友您旅途辛苦了！小蓝贴心为您准备了以下暖心服务，加注量达到10公斤后，您可以
          <text style="color: red">任意选择其一服务，</text>
          我们将提前准备，静候您的到来，祝您一路顺风！
        </view>
        <view class="lbl-box">
          <view
            v-for="(item, index) in giftArr"
            :key="index"
            class="flex-center lbl"
            :class="gift === item.id ? 'picked' : ''"
            @click="pickGift(item.id)"
          >
            {{ item.name }}
            <view class="flex-center" :class="gift === item.id ? 'picked-mark' : 'dn'">
              <uni-icons type="checkmarkempty" color="#fff" size="18"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      <view class="card note-box" style="border-radius:5px;">
        <view style="font-size: 32rpx">留言备注</view>
        <textarea
          v-model="note"
          placeholder="请输入您的留言"
          placeholder-style="color: #999;font-size: 30rpx"
          auto-height
          class="note-textarea"
        ></textarea>
      </view>
      <view class="flex-hcenter"><view class="flex-center btn-box" @click="appointment">提交预约</view></view>
    </view>
  </view>
  <!-- 预约时间弹框 -->
  <uni-popup ref="TimePickerPopup" type="bottom" background-color="#fff" :is-mask-click="false">
    <TimePicker ref="TimePickerRef" @cancel="closeTimePicker" @confirm="confirmTime" />
  </uni-popup>
  <!-- 车牌弹框 -->
  <uni-popup ref="VehiclePlatePickerPopup" type="bottom" background-color="#fff">
    <VehiclePlatePicker :plate="plateNumber" @add="toAddPlate" @pick="confirmPlate" />
  </uni-popup>
  <!-- 加注量弹框 -->
  <uni-popup ref="WeightPickerPopup" type="center">
    <WeightPicker :weight="weight" @custom-input="openWeightInput" @pick="confirmWeight" />
  </uni-popup>
  <!-- 自定义加注量弹框 -->
  <uni-popup ref="CustomWeightInputPopup" type="center" :is-mask-click="false">
    <view class="weight-input-box">
      <view class="popup-weight-title-box">请输入加注量(公斤)</view>
      <view class="flex-vcenter popup-weight-input-box">
        <input class="weight-input" v-model="customWeight" type="number" maxlength="3" />
      </view>
      <view class="popup-weight-btn-box">
        <BtnCancel @cancel="closeWeightInput" />
        <BtnConfirm @confirm="confirmWeightInput" />
      </view>
    </view>
  </uni-popup>
  <!-- 加注机弹框 -->
  <uni-popup ref="MachinePickerPopup" type="bottom" background-color="#fff">
    <view class="machine-picker-box">
      <scroll-view scroll-y="true" style="max-height: 700rpx">
        <MachinePicker @pick="pickMachine" :list="machineStore.fixedList" />
      </scroll-view>
    </view>
  </uni-popup>
  <!-- 汽车车牌 -->
  <VehiclePlatePad v-if="isShowPlatePad" @cancel="isShowPlatePad = false" @confirm="confirmPlate" />
  <!-- 绑定手机号码弹框 -->
  <uni-popup ref="PhonePadPopup" type="bottom" :is-mask-click="false"><PhonePad @close="closePhonePad" /></uni-popup>
  <view v-if="curPage === 'map'"><web-view :src="mapURI"></web-view></view>
</template>

<script setup lang="ts">
import { isWeChatMP } from '@/utils/platform';
import environment from '@c/pobulic/environment.vue';
import { fillingMachineAddress, giftList } from '@/gql/filling';
import { useAddressStore } from '@/stores/address';
import { getDriverID } from '@/stores/driverID';
import { useUserStore } from '@/stores/user';
import { useMachineStore } from '@/stores/machine';
import { useVehicleStore } from '@/stores/vehicle';
import { navTo, redirectTo } from '@/utils/navigator';
import { errorToast, showLoading, showToast } from '@/utils/prompt';
import MachinePicker from '@c/appointment/MachinePicker.vue';
import TimePicker from '@c/appointment/TimePicker.vue';
import VehiclePlatePicker from '@c/appointment/VehiclePlatePicker.vue';
import WeightPicker from '@c/appointment/WeightPicker.vue';
import BtnCancel from '@c/common/BtnCancel.vue';
import BtnConfirm from '@c/common/BtnConfirm.vue';
import VehiclePlatePad from '@c/common/VehiclePlatePad.vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import PhonePad from '@c/common/PhonePad.vue';
import { toPublish } from '@mqtt';
import { computed, reactive, Ref, ref, watch } from 'vue';

// #ifdef H5
import { defaultFail, getLocation } from '@/utils/wechat.jssdk';
// #endif

// static
const driver_id = getDriverID();
const userInfo = useUserStore();
const vehicleStore = useVehicleStore();
const machineStore = useMachineStore();
const plateList = computed(() => vehicleStore.plateList);
const addressStore = useAddressStore();
const giftArr: Ref<any[]> = ref([]);

const PhonePadPopup = ref(null);
const repeat = ref(true); //放重复点击

const name = ref('');
const phone = ref('');
const Locposition = ref('');
const Detailed = ref('');
// data
let type = '';
let machineID = '';
const isShowPlatePad = ref(false);
const curTab: Ref<'station' | 'delivery'> = ref('delivery');
const isStation = computed(() => curTab.value === 'station');
const isDelivery = computed(() => curTab.value === 'delivery');
const time = ref('');
let start = '';
let end = '';
const plateNumber = ref('');
const popupDelayClose = 400;

if (plateList.value.length === 0) {
  vehicleStore.getPlateList();
  const plateListWatchStopHandle = watch(plateList, () => {
    if (plateList.value.length === 1) {
      plateNumber.value = plateList.value[0];
    }
    plateListWatchStopHandle();
  });
} else if (plateList.value.length === 1) {
  plateNumber.value = plateList.value[0];
}

const weight: Ref<number> = ref(null);
const customWeight = ref('');
// 更改地址
const lat = ref();
const lon = ref();
const addrLocation = ref('');
const curPage: Ref<'form' | 'map'> = ref('form');
const mapURI = ref('');

const stationInfo = reactive({
  address: '',
  consignee: '',
  latitude: null as number,
  longitude: null as number,
  location: '',
  phone: '',
});
const deliveryInfo = computed(() => addressStore.deliveryInfo);

const curInfo = computed(() => (isStation.value ? stationInfo : deliveryInfo.value));

const gift = ref('');
const note = ref('');

// refs
const TimePickerPopup = ref(null);
const TimePickerRef = ref(null);
const VehiclePlatePickerPopup = ref(null);
const WeightPickerPopup = ref(null);
const CustomWeightInputPopup = ref(null);
const MachinePickerPopup = ref(null);

getGiftList();
onShow(() => {
  getDefaultDeliveryInfo();
});

onLoad((options) => {
  if (!uni.getStorageSync('storage_key').id || !driver_id) {
    uni.setStorageSync('storage', 'user');
    uni.reLaunch({
      url: '/pages/login/login',
    });
    return;
  }
  userInfo.getUserInfo();
  type = options.type;
  machineID = options.id;
  if (type !== 'delivery') {
    curTab.value = 'station';
    getMachineAddress(machineID);
  } else {
    getDefaultDeliveryInfo();
  }

});

function getGiftList() {
  const payload = { query: giftList };
  toPublish('ql/driver/getgoodsList', payload, (obj: any) => {
    giftArr.value = obj.data.goods_list;
  });
}

function getMachineAddress(id: string) {
  const payload = {
    query: fillingMachineAddress,
    variables: { id },
  };
  toPublish('ql/driver/fillingMachineInfo', payload, (obj: any) => {
    const { fill } = obj.data;
    stationInfo.location = fill.code;
    stationInfo.address = fill.address;
    stationInfo.latitude = fill.latitude;
    stationInfo.longitude = fill.longitude;
  });
}

function getDefaultDeliveryInfo() {
  if (addressStore.list.length === 0) {
    addressStore.getList(addressStore.setDefaultDeliveryInfo);
  } else {
    addressStore.setDefaultDeliveryInfo();
  }
}

function switchTab(tab: 'station' | 'delivery') {
  curTab.value = tab;
}
// TimePicker
function openTimePicker() {
  TimePickerPopup.value.open();
  // #ifdef MP-WEIXIN
  TimePickerRef.value.onShow();
  // #endif
}
function closeTimePicker() {
  TimePickerPopup.value.close();
}
/**
 * 选择预约的时间
 */
function confirmTime(info: { [T: string]: string }) {
  start = info.start;
  end = info.end;
  time.value = info.timeText;
  closeTimePicker();
}
// VehiclePlatePicker
function openPlatePicker() {
  VehiclePlatePickerPopup.value.open();
}
function closePlatePicker() {
  VehiclePlatePickerPopup.value.close();
}
function toAddPlate() {
  closePlatePicker();
  isShowPlatePad.value = true;
}
function confirmPlate(plate) {
  plateNumber.value = plate;
  setTimeout(() => {
    isShowPlatePad.value = false;
    closePlatePicker();
  }, popupDelayClose);
}
// WeightPicker
function openWeightPicker() {
  WeightPickerPopup.value.open();
}
function closeWeightPicker() {
  WeightPickerPopup.value.close();
}
function openWeightInput() {
  closeWeightPicker();
  CustomWeightInputPopup.value.open();
}
function closeWeightInput() {
  customWeight.value = '';
  CustomWeightInputPopup.value.close();
}
function confirmWeight(value) {
  weight.value = value;
  setTimeout(closeWeightPicker, popupDelayClose);
}
function confirmWeightInput() {
  const value = Number.parseInt(customWeight.value);
  if (Number.isNaN(value)) {
    showToast('请输入加注量');
  } else if (value < 10) {
    showToast('至少预约10公斤');
  } else {
    weight.value = Number.parseInt(customWeight.value);
    closeWeightInput();
  }
}
// MachinePicker
function openMachinePicker() {
  showLoading();
  machineStore.toGetList();
  MachinePickerPopup.value.open();
}
function closeMachinePicker() {
  MachinePickerPopup.value.close();
}
function pickMachine(info) {
  stationInfo.location = info.name;
  stationInfo.address = info.address;
  stationInfo.longitude = info.longitude;
  stationInfo.latitude = info.latitude;
  machineID = info.id;
  closeMachinePicker();
}
// gift
function pickGift(value) {
  gift.value = gift.value === value ? '' : value;
}
// appointment
function clearData() {
  time.value = '';
  start = '';
  end = '';
  plateNumber.value = '';
  weight.value = null;
  gift.value = '';
  note.value = '';
  addressStore.clearDeliveryInfo();
}
function checkForm() {
  const los = Locposition.value ? Locposition.value : deliveryInfo.value.location;
  const hasLocation = isStation.value ? stationInfo.location !== '' : los !== '';
  const isAllFilled = start !== '' && weight.value !== null && hasLocation;
  // && plateNumber.value !== ''
  // const weightValue = Number.parseInt(weight.value);
  // if (weightValue < 10) {
  //   showToast('至少预约10公斤');
  //   return false;
  // }
  if (!isAllFilled) {
    showToast('请将信息填写完整');
  }
  return isAllFilled;
}
function openPhonePad() {
  PhonePadPopup.value.open();
}
function closePhonePad() {
  PhonePadPopup.value.close();
}
function appointment() {
  if (checkForm()) {
    const mobile = phone.value
      ? phone.value
      : curInfo.value.phone ? curInfo.value.phone : userInfo.mobile ? userInfo.mobile : '';
    const isPhoneNumber = /^1[3-9]\d{9}$/.test(mobile);
    if (!isPhoneNumber) {
      showToast('请填写有效的手机号');
      return false;
    }
    const fullName = name.value
      ? name.value
      : curInfo.value.consignee ? curInfo.value.consignee : userInfo.realname ? userInfo.realname : '';
    if (!fullName) {
      showToast('请填写您的姓名');
      return false;
    }
    const abbreviate = Locposition.value ? Locposition.value : deliveryInfo.value.location;
    showLoading('正在预约');
    if (!repeat.value) {
      return;
    }
    repeat.value = false;
    const count = weight.value;
    const payload = {
      driver_id,
      order_type: 'subscribe',
      type: isStation.value ? 'store' : 'delivery',
      count,
      platform: 'wechat',
      start,
      end,
      cart_code: '',
      latitude: lat.value ? lat.value : curInfo.value.latitude,
      longitude: lon.value ? lon.value : curInfo.value.longitude,
      abbreviate,
      address: Detailed.value ? Detailed.value : curInfo.value.address,
      name: fullName,
      mobile,
      des: note.value,
      shop_goods_id: gift.value,
      fill_id: isStation.value ? machineID : 0,
    };
    toPublish('order_subscribe/addOrder', payload, (obj: any) => {
      const { code } = obj;
      if (code === 1) {
        repeat.value = true
        clearData();
        redirectTo('appointment/success');
      } else {
        repeat.value = true
        errorToast('预约失败');
      }
    });
  }
}

function chooseLocation() {
  mapURI.value = `https://apis.map.qq.com/tools/locpicker?coord=${lat.value},${
    lon.value
  }&search=1&type=1&key=URFBZ-F4TKI-SLPGX-57GMO-ZHYM6-BCFSL&referer=安蓝环保`;
  curPage.value = 'map';

  function msgListener(event) {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    const data = event.data;
    console.log(data);
    if (data && data.module == 'locationPicker') {
      //防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
      // location.value = `${data.poiaddress}-${data.poiname}`;
      lon.value = Number(data.latlng.lng);
      lat.value = Number(data.latlng.lat);
      addrLocation.value = data.poiaddress;
      Detailed.value = data.poiaddress;
      Locposition.value = data.poiname;
      curPage.value = 'form';
      window.removeEventListener('message', msgListener);
    }
  }
  window.addEventListener('message', msgListener, false);
}

function openMap() {
  showLoading('加载中');
  function success(res: any) {
    uni.hideLoading();
    lat.value = Number.parseFloat(res.latitude);
    lon.value = Number.parseFloat(res.longitude);
    chooseLocation();
  }
  function fail() {
    // TODO
    showToast('请允许位置权限帮您准确定位');
    setTimeout(() => {
      uni.getLocation({
        type: 'gcj02',
        altitude: true,
        success(res) {
          uni.hideLoading();
          lon.value = Number(res.longitude);
          lat.value = Number(res.latitude);
          chooseLocation();
        },
      });
    }, 2000);
  }
  getLocation(success, defaultFail('getLocation', fail));
}
</script>

<style scoped lang="less">
.c-999 {
  color: #999;
}

.box {
  width: 96%;
  font-family: 'PingFang SC';
  padding-bottom: 114rpx;
}

.card {
  background: white;
  box-shadow: 0rpx 0rpx 51rpx 0rpx rgba(179, 179, 179, 0.25);
  border-radius: 30rpx 30rpx 5px 5px;
  position: relative;
  margin-top: 30rpx;
  padding-top: 104rpx;

  .tab-box {
    width: 100%;
    height: 124rpx;
    position: absolute;
    top: -20rpx;
    background-repeat: no-repeat;
    background-size: cover;
    display: grid;
    grid-template-columns: repeat(2, 345rpx);

    &.station {
      background-image: url(../../static/appointment/tab-left.png);
    }

    &.delivery {
      background-image: url(../../static/appointment/tab-right.png);
    }

    .tab {
      font-size: 34rpx;
      color: #333;
      padding-top: 8rpx;
    }

    .active {
      font-size: 36rpx;
      color: #1d92ff;
    }
  }
}

.item-box {
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  font-size: 32rpx;
  color: #333;
  display: grid;
  grid-template-columns: 130rpx 470rpx;
  column-gap: 30rpx;
  align-items: center;

  &.split-line {
    border-bottom: 2rpx solid rgba(238, 238, 238, 0.6);
  }

  .pick-block {
    display: grid;
    grid-template-columns: 420rpx 50rpx;
  }

  .map-address-block {
    display: grid;
    grid-template-columns: 420rpx 50rpx;
    align-items: center;
  }
}

.gift-box {
  margin-top: 30rpx;
  padding: 40rpx 30rpx 66rpx;

  .title {
    font-size: 32rpx;
    color: #333;
  }

  .content {
    margin-top: 30rpx;
    font-size: 28rpx;
    color: #666;
    line-height: 36rpx;
  }

  .lbl-box {
    margin-top: 44rpx;
    display: grid;
    grid-template-columns: repeat(3, 192rpx);
    column-gap: 27rpx;

    .lbl {
      height: 76rpx;
      border: 2rpx solid rgba(179, 179, 179, 0.25);
      box-shadow: 0rpx 0rpx 51rpx 0rpx rgba(179, 179, 179, 0.25);
      border-radius: 5px;
      position: relative;
      overflow: hidden;

      .picked-mark {
        width: 32rpx;
        height: 24rpx;
        background: linear-gradient(104deg, #41a3ff, #1b91ff);
        border-radius: 0rpx 0rpx 0rpx 5px;
        position: absolute;
        top: 0;
        right: 0;
      }
    }

    .lbl.picked {
      color: #1b91ff;
      border-color: #1b91ff;
    }
  }
}

.note-box {
  margin-top: 15rpx;
  padding: 20rpx;
  .note-textarea {
    font-size: 30rpx;
    margin-top: 32rpx;
    width: 100%;
  }
}

.btn-box {
  margin-top: 70rpx;
  width: 370rpx;
  height: 80rpx;
  background: linear-gradient(104deg, #41a3ff, #1b91ff);
  border-radius: 5px;
  font-size: 36rpx;
  letter-spacing: 4rpx;
  color: white;
}

.weight-input-box {
  background-color: #fff;
  border-radius: 5px;
}

.popup-weight-title-box {
  padding: 30rpx 24rpx;
  font-size: 34rpx;
  color: #333;
}

.popup-weight-input-box {
  margin: 0 34rpx;
  height: 100rpx;
  border: 2rpx solid #666;
  border-radius: 5px;
  padding: 0 28rpx;

  .weight-input {
    width: 100%;
    font-size: 40rpx;
  }
}

.popup-weight-btn-box {
  display: grid;
  grid-template-columns: repeat(2, 275rpx);
  column-gap: 30rpx;
  padding: 40rpx 30rpx;
}

.machine-picker-box {
  padding: 30rpx 10rpx 0;
}
.informatio {
  width: 100%;
  margin: 15rpx 0px;
  border-radius: 5px;
  background: white;
  view:nth-of-type(1) {
    border-bottom: 1px solid #eee;
  }
  view {
    padding: 30rpx;
    box-sizing: border-box;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text {
      font-size: 32rpx;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #333333;
    }
    input {
      width: 60%;
      text-align: right;
      font-size: 32rpx;
    }
  }
}
.detail-textarea {
  text-align: right;
}
</style>
